package com.example.dirviesystem.student.controller;

import com.example.dirviesystem.config.R;
import com.example.dirviesystem.entity.*;
import com.example.dirviesystem.repository.*;
import com.example.dirviesystem.student.pojo.ApplicationDto;
import com.example.dirviesystem.student.pojo.ChangePassword;
import com.example.dirviesystem.student.service.OssOpe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/student")
@Slf4j
public class stuControl {
    @Autowired
    private StudentInfoRe stuRe;
    @Autowired
    private DrivingTypeRe drTypeRe;
    @Autowired
    private OssOpe ossOpe;
    @Autowired
    private ApplicationFormRe applicationFormRe;
    @Autowired
    private StudentMessageRep messageRep;
    @Autowired
    private DrivingProgressRepository drivingProgressRepository;

    /**
     * 修改学生信息
     */
    @PutMapping("/updateStudentInfo")
    public R<Object> updateStudentInfo(@RequestBody StudentInfo studentInfo)throws Exception {
        log.debug(studentInfo.toString());
        StudentInfo save = stuRe.save(studentInfo);
        return R.success(save);
    }

    /**
     * 修改密码
     */
    @PutMapping("/changePassword")

    public R<Object> changePassword(@RequestBody ChangePassword changePassword)throws Exception {
        log.debug(changePassword.toString());
        StudentInfo studentInfo = stuRe.findByAndIdNumberAndPassword(changePassword.getIdNumber(), changePassword.getOldPassword());
        if (studentInfo == null) {
            return R.fail("原密码错误");
        }else {
            studentInfo.setPassword(changePassword.getNewPassword());
            StudentInfo save = stuRe.save(studentInfo);
            return R.success(save);
        }
    }

    /**
     * 获取驾照类型
     * @return
     * @throws Exception
     */
    @GetMapping("/getDrivingType")
    public R<List<DrivingType>> getDrivingType()throws Exception{

        return R.success(drTypeRe.findAll());
    }

    /**
     * 上传文件
     */
    @PostMapping("/material/upload")
    public R<String> uploadMaterial(@RequestParam("file") MultipartFile file,
                                 @RequestParam("materialKey") String materialKey) {
        log.info("上传文件: {}, 类型: {}", file.getOriginalFilename(), materialKey);
        String url = ossOpe.uploadFilePublicDocu(file);
        if (url != null) {
            return R.success(url);
        } else {
            return R.fail("上传失败");
        }
    }

    /**
     * 删除文件
     */
    @PostMapping("/material/delete")
    public R<String> deleteMaterial(@RequestBody Map<String, String> body) throws Exception {
        System.out.println("删除文件");
        log.info("删除文件: {}", body.get("url"));
        String url = body.get("url");
        if (url == null || url.isEmpty()) {
            return R.fail("缺少文件URL");
        }
        ossOpe.deleteFile(url);
        return R.success(null);
    }

    /**
     * 学生提交申请
     * */
    @PostMapping("/submitApply")
    public R<Object> submitApply(@RequestBody ApplicationDto applicationDto){
        log.info("学生申请表单："+applicationDto.toString());
        ApplicationForm applicationForm = new ApplicationForm();
        applicationForm.setId(applicationDto.getId());
        applicationForm.setStudent(applicationDto.getStudentInfo());
        applicationForm.setApproved(applicationDto.getApproved());
        applicationForm.setDrivingType(applicationDto.getType());
        applicationForm.setPreferredCoach(applicationDto.getPreferredCoach());
        //材料表
        applicationForm.setIdCardCopyPath(applicationDto.getMaterialDto().getIdCardCopyPath());
        applicationForm.setHealthReportPath(applicationDto.getMaterialDto().getHealthReportPath());
        applicationForm.setDrivingLicensePath(applicationDto.getMaterialDto().getDrivingLicensePath());
        applicationForm.setAccidentFreeProofPath(applicationDto.getMaterialDto().getAccidentFreeProofPath());
        applicationForm.setEducationCertificatePath(applicationDto.getMaterialDto().getEducationCertificatePath());

        ApplicationForm saved = applicationFormRe.save(applicationForm);
        StudentMessage studentMessage = new StudentMessage();
        studentMessage.setStudent(applicationForm.getStudent());
        if(applicationDto.getId()!=null){
            studentMessage.setContent("您已提交修改，请等待管理员审核，后续请注意通知消息");
        }else {
            studentMessage.setContent("您已提交报名，请等待审核");
        }
        studentMessage.setCreateTime(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
        studentMessage.setLook(false);

        messageRep.save(studentMessage);
        return R.success(saved);
    }
    /**
     * 判断学生是否报名过
     */
    @GetMapping("/isSubmit/{id}")
    public R<Boolean> isSubmit(@PathVariable Long id){
        ApplicationForm applicationForm = applicationFormRe.findByStudentId(id);
        System.out.println(applicationForm);
        if (applicationForm == null){
            return R.success(false);
        }else {
            return R.success(true);
        }
    }
    /**
     * 获取学生报名信息
     */
    @GetMapping("/getApply/{id}")
    public R<ApplicationForm> getApply(@PathVariable Long id) throws Exception{
        ApplicationForm applicationForm = applicationFormRe.findByStudentId(id);
        if(applicationForm == null){
            return R.fail("未报名");
        }
        return R.success(applicationForm);
    }
    /**
     * 学生获取未读消息
     */
    @GetMapping("/getUnreadMessage/{id}")
    public R<List<StudentMessage>> getUnreadMessage(@PathVariable Long id){
        List<StudentMessage> studentMessages = messageRep.findByStudentIdAndLook(id, false);
        log.info(studentMessages.toString());
        return R.success(studentMessages);
    }
    /**
     * 学生获取已读消息
     */
    @GetMapping("/getReadMessage/{id}")
    public R<List<StudentMessage>> getReadMessage(@PathVariable Long id) {
        List<StudentMessage> studentMessages = messageRep.findByStudentIdAndLook(id, true);
        return R.success(studentMessages);
    }

    /**
     * 标记消息为已读
     * @param id
     * @return
     */
    @DeleteMapping("/markReadMessage/{id}")
    public R<String> markMessageAsRead(@PathVariable Long id) {
        Optional<StudentMessage> optionalMessage = messageRep.findById(id);
        if (optionalMessage.isEmpty()) {
            return R.fail("消息不存在");
        }
        StudentMessage message = optionalMessage.get();
        if (Boolean.TRUE.equals(message.getLook())) {
            return R.success("消息已是已读状态");
        }
        message.setLook(true);
        messageRep.save(message);
        return R.success("消息标记为已读");
    }
    /**
     * 删除已读消息
     */
    @DeleteMapping("/deleteMessage/{id}")
    public R<String> deleteMessage(@PathVariable Long id) {
        Optional<StudentMessage> optionalMessage = messageRep.findById(id);
        if (optionalMessage.isPresent()) {
            StudentMessage message = optionalMessage.get();
            if (Boolean.TRUE.equals(message.getLook())) {
                messageRep.deleteById(id);
                return R.success("消息删除成功");
            } else {
                return R.fail("仅已读消息可删除");
            }
        } else {
            return R.fail("消息不存在");
        }
    }

    @GetMapping("/coaches/{coachId}/students")
    public R<Page<StudentInfo>> getStudentsByCoachId(
            @PathVariable Long coachId,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Page<StudentInfo> students = stuRe.findAllByCoachIdAndName(
                coachId,
                name,
                PageRequest.of(page, size)

        );
        return R.success(students);
    }

    /**
     * 获取学员的科目通过数量
     */
    @GetMapping("/passed-count/{studentId}")
    public R<Integer> getPassedSubjectCount(@PathVariable Long studentId) {
        StudentInfo student = stuRe.findById(studentId)
                .orElseThrow(() -> new RuntimeException("Student not found"));

        DrivingProgress progress = drivingProgressRepository.findByStudent(student)
                .orElseThrow(() -> new RuntimeException("Driving progress not found"));

        int count = 0;
        if (progress.isSubjectOnePassed()) count++;
        if (progress.isSubjectTwoPassed()) count++;
        if (progress.isSubjectThreePassed()) count++;
        if (progress.isSubjectFourPassed()) count++;
        return R.success(count);
    }


}
